package business;
import java.io.Serializable;
import java.util.List;

import model.Associado;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

public class AssociadoDAO implements Serializable {
	private static final long serialVersionUID = 3712477904752443488L;
	static AssociadoDAO instance;
	
	public static AssociadoDAO getInstance()
	{
		if(instance == null)
			instance = new AssociadoDAO();
		return instance;
	}
	public AssociadoDAO()
	{
	}
	public Associado get(int id) 
	{		
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		Associado item = (Associado)session.get(Associado.class,id);		
		tr.commit();
		return item;
	}
	public void salvar(Associado associado)
	{
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		session.saveOrUpdate(associado);
		tr.commit();
		return;
	}
	public  void remover(int id)
	{
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		session.delete(session.get(Associado.class, id));
		tr.commit();
		return ;
	}
	@SuppressWarnings("unchecked")
	public List<Associado> listar() 
	{
		List<Associado> lista;
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		Criteria cr = session.createCriteria(Associado.class);
		cr.addOrder(Order.asc("nome"));
		lista = cr.list();
		tr.commit();
		return lista;
	}
	@SuppressWarnings({ "unchecked" })
	public List<Associado> listar(String nome) 
	{
		List<Associado> lista;
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		Criteria cr = session.createCriteria(Associado.class);
		cr.add(Restrictions.ilike("nome", nome));
		cr.addOrder(Order.asc("nome"));
		lista = cr.list();
		tr.commit();
		return lista;
	}
}